import os
import re

# 文件夹路径
folder_path = "./Animation/AnimationBlueprint/AnimNode"

# 输出文件路径
output_file_path = "./Animation/AnimationBlueprint/AnimNode/!Overview.md"

# Mermaid ClassDiagram 正则表达式
mermaid_class_diagram_regex = r"```mermaid\nclassDiagram\n(.*?)\n```"

# 创建用于存储所有 Mermaid ClassDiagram 代码的列表
all_mermaid_lines = []

# 遍历文件夹中的所有文件
for filename in os.listdir(folder_path):
    if filename.endswith(".md"):
        file_path = os.path.join(folder_path, filename)
        with open(file_path, "r", encoding="utf-8") as f:
            content = f.read()

        # 提取 Mermaid ClassDiagram 代码
        mermaid_pattern = r"```mermaid\nclassDiagram\n(.*?)```"
        mermaid_code = re.findall(mermaid_pattern, content, re.DOTALL)
        for code in mermaid_code:
            for line in code.strip().split("\n"):
                # 去除前后空格和 \t 字符
                stripped_line = line.strip()
                if stripped_line:
                    all_mermaid_lines.append(stripped_line)

# 对所有 Mermaid ClassDiagram 代码行进行去重
unique_mermaid_lines = set(all_mermaid_lines)

# 将带有 "class" 前缀的行和其他行分开
class_lines = []
other_lines = []
for line in unique_mermaid_lines:
    if line.startswith("class "):
        class_lines.append(line)
    else:
        other_lines.append(line)

# 创建 !Overview.md 文件并写入去重后的 Mermaid ClassDiagram 代码
with open(output_file_path, "w", encoding="utf-8") as f:
    f.write("# Class Diagram Overview\n\n```mermaid\nclassDiagram\n")
    for line in class_lines:
        f.write(line + "\n")
    for line in other_lines:
        f.write(line + "\n")
    f.write("```")

print("Mermaid ClassDiagram code has been merged into !Overview.md file.")